<template>
	<v-navigation-drawer fixed right width="600px" v-model="visible" temporary hide-overlay>
		<v-flex class="d-flex align--center pa-4">
			<div class="title flex-fill">权限设置</div>
			<div>
				<v-btn color="primary" class="mr-3" @click="onSave" :loading="confirmLoading">保存</v-btn>
				<v-btn icon @click="visible = !visible">
					<v-icon>fa-times</v-icon>
				</v-btn>
			</div>
		</v-flex>
		<v-divider/>
		<v-container>
			<md-tree-view v-model="role.menuIds" :options="tree"/>
		</v-container>
	</v-navigation-drawer>
</template>

<script>
import MdDialogMixins from '@/common/mixins/MdDialogMixins';
import MenuApi from '@/common/api/MenuApi';
import RoleMenuApi from '@/common/api/RoleMenuApi';
import MdTreeView from '@/components/selector/MdTreeView';

export default {
	name: 'RoleMenuDialog',
	components: {MdTreeView},
	mixins: [MdDialogMixins],
	data() {
		return {
			visible: false,
			selectMenu: [],
			tree: [],
			role: {
				id: undefined,
				menuIds: []
			}
		}
	},
	methods: {
		getMenuList() {
			MenuApi.list({list: 'true'}).then(res => {
				this.$utils.responseHandler(res).then(({data}) => {
					if (!data) {
						this.tree = [];
					}
					this.tree = this.buildTree(data);
				})
			})
		},
		buildTree(data = []) {
			return data.map(item => {
				return {id: item.id, name: item.menuName, pid: item.parentId || '0'}
			})
		},
		edit(id) {
			this.role = {
				id: undefined,
				menuIds: []
			}
			this.getMenuList();
			this.visible = true;
			this.getRoleMenu(id)
		},
		getRoleMenu(id) {
			RoleMenuApi.get(id).then(res => {
				this.$utils.responseHandler(res).then(({data}) => {
					if (!data.menuIds) data.menuIds = []
					this.role = data;
				}).catch(() => this.visible = false);
			}).catch(() => this.visible = false);
		},
		onSave() {
			this.confirmLoading = true;
			RoleMenuApi.create({rolesId: this.role.id, menuIds: this.role.menuIds}).then(res => {
				this.$utils.responseHandler(res, true, true).then(() => {
					this.visible = false;
				})
			}).finally(() => this.confirmLoading = false)
		}
	}
}
</script>

<style scoped>

</style>